package com.example.demo.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;

@ControllerAdvice
public class ExceptionAdviceController {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ModelAndView error(RuntimeException error, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String content = "";
        try {
            String errorMsg = error.getMessage();
            response.setStatus(Integer.valueOf(errorMsg.split(",")[0]));
            content =  "{\"message\":\"" + errorMsg.split(",")[1] + "\", \"server_time\": \"" + "" + new Date(System.currentTimeMillis()) + "\"}";
        } catch (Exception e) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            content =  "{\"message\":\"" + error.getMessage() + "\", \"server_time\": \"" + "" + new Date(System.currentTimeMillis()) + "\"}";
        }
        PrintWriter writer = response.getWriter();
        writer.write(content);
        writer.flush();
        return null;
    }
}
